package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author kfzhao
 * @version 1.0
 * @className FileController
 * @description
 * @date 2021/12/25 13:43
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(@RequestBody MultipartFile file) {
        try {
            // 1 判断当前的文件是否存在
            if (file == null) {
                throw new RuntimeException("当前文件不存在");
            }
            // 2 获取当前文件的完整名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("当前文件不存在");
            }
            // 3 获取当前文件的扩展名称
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 4 获取文件内容
            byte[] content = file.getBytes();
            // 5 创建文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extName);
            // 6 基于工具类进行文件上传，并接收返回参数，String[]
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            // 7 封装返回结果
            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];
            return new Result(true, StatusCode.OK, "文件上传成功", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}
